package com.frogs.ucenter.v1.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.SexEnum;
import com.frogs.system.util.UserFamilyStatusEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.RequestIllegalException;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.TagBaseInfoDao;
import com.frogs.ucenter.dao.TagFamilyMemberRelationDao;
import com.frogs.ucenter.dao.UserFamilyMemberDao;
import com.frogs.ucenter.entity.TagBaseInfo;
import com.frogs.ucenter.entity.TagFamilyMemberRelation;
import com.frogs.ucenter.entity.UserFamilyMember;
import com.frogs.ucenter.v1.request.UserFamilyMemberAddRequest;
import com.frogs.ucenter.v1.request.UserFamilyMemberDeleteRequest;
import com.frogs.ucenter.v1.request.UserFamilyMemberListRequest;
import com.frogs.ucenter.v1.request.UserFamilyMemberShowRequest;
import com.frogs.ucenter.v1.request.UserFamilyMemberTagShowRequest;
import com.frogs.ucenter.v1.request.UserFamilyMemberUpdateRequest;
import com.frogs.ucenter.v1.response.AddResponse;
import com.frogs.ucenter.v1.response.DeleteResponse;
import com.frogs.ucenter.v1.response.ListResponse;
import com.frogs.ucenter.v1.response.PageListResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.response.UpdateResponse;
import com.frogs.ucenter.v1.service.UserFamilyMemberService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"userFamilyMemberService")
public class UserFamilyMemberServiceImpl implements UserFamilyMemberService {
    @Resource
    private UserFamilyMemberDao userFamilyMemberDao;
    
    @Resource
    private TagFamilyMemberRelationDao tagFamilyMemberRelationDao;
    
    @Resource 
    private TagBaseInfoDao tagBaseInfoDao;

    private static final Logger log = LoggerFactory.getLogger(UserFamilyMemberServiceImpl.class);

	@Override
	public Response getPageList(Request request) throws Exception{
		PageListResponse<UserFamilyMember> response = new PageListResponse<UserFamilyMember>();
    	
    	try {
    		UserFamilyMemberListRequest listRequest = (UserFamilyMemberListRequest)request;
    		
    		HashMap<String,Object> params = new HashMap<String,Object>();
    		params.put("eqUserId",listRequest.getUserId() );
    		params.put("eqStatus",UserFamilyStatusEnum.AVAILABILITY_YES.getId() );
    		params.put("orderByClause"," id DESC" );
    		PageList<UserFamilyMember> list = userFamilyMemberDao.selectByMap(params, listRequest.getPageNum(), listRequest.getNumPerPage());
    		response.setPageTurn(list.getPageTurn());
    		response.setList(list);
	    	response.setTip("用户家庭成员查询成功");
	    } catch (Exception e) {
	    	log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}

	@Override
	public Response getObject(Request request) throws Exception{
		ShowResponse<UserFamilyMember> response = new ShowResponse<UserFamilyMember>();
    	
    	try {
    		UserFamilyMemberShowRequest showRequest = (UserFamilyMemberShowRequest)request;
    		UserFamilyMember info = userFamilyMemberDao.selectById(showRequest.getId());
    		if(info.getStatus() == UserFamilyStatusEnum.AVAILABILITY_NO.getId()) {
    			throw new RequestIllegalException("family member has bean deleted,error code" + info.getStatus());
    		}
    		response.setInfo(info);
	    	response.setTip("用户家庭成员查询成功");
	    } catch (Exception e) {
	    	log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}

	@Override
	public Response update(Request request) throws Exception{
		UpdateResponse<UserFamilyMember> response = new UpdateResponse<UserFamilyMember>();
    	
    	try {
    		UserFamilyMemberUpdateRequest updateRequest = (UserFamilyMemberUpdateRequest)request;
    		UserFamilyMember info = userFamilyMemberDao.selectById(updateRequest.getId());
    		
    		if(info.getUserId().intValue() != updateRequest.getUserId()){
	    		throw new RequestIllegalException("error userId:"+updateRequest.getUserId());
	    	}
    		
    		info.setAgeLowerLimit(updateRequest.getAgeLowerLimit());
    		info.setAgeUpperLimit(updateRequest.getAgeUpperLimit());
    		info.setDiseaseTag(updateRequest.getDiseaseTag());
    		info.setHealthConditionTag(updateRequest.getHealthConditionTag());
    		info.setHealthInsuranceInfo(updateRequest.getHealthInsuranceInfo());
    		info.setIdentityCard(updateRequest.getIdentityCard());
    		info.setIdentityType(updateRequest.getIdentityType());
    		info.setMedicationContraindicationsTag(updateRequest.getMedicationContraindicationsTag());
    		info.setName(updateRequest.getName());
    		info.setOtherTag(updateRequest.getOtherTag());
    		info.setRank(updateRequest.getRank());
    		info.setWeight(updateRequest.getWeight());
    		info.setHeight(updateRequest.getHeight());
    		info.setPhone(updateRequest.getPhone());
    		if(!StringUtil.isEmpty(updateRequest.getBirthday())) {
    			info.setBirthday(updateRequest.getBirthday());
    		}
    		if(!StringUtil.isEmpty(updateRequest.getRelatives())) {
    			info.setRelatives(updateRequest.getRelatives());
    		}
    		if(SexEnum.UNKNOW.getId() != updateRequest.getSex()) {
    			info.setSex(updateRequest.getSex());
    		}
    		if(-1 != updateRequest.getAge()) {
    			info.setAge(updateRequest.getAge());
    		}
    		
    		JSONObject allObject = new JSONObject();
    		if(!StringUtil.isEmpty(info.getDiseaseTag())){
    			allObject.putAll((JSONObject)JSON.parse(info.getDiseaseTag()));
    		}
    		if(!StringUtil.isEmpty(info.getHealthConditionTag())){
    			allObject.putAll((JSONObject)JSON.parse(info.getHealthConditionTag()));
    		}
    		if(!StringUtil.isEmpty(info.getOtherTag())){
    			allObject.putAll((JSONObject)JSON.parse(info.getOtherTag()));
    		}
    		if(!StringUtil.isEmpty(info.getMedicationContraindicationsTag())){
    			allObject.putAll((JSONObject)JSON.parse(info.getMedicationContraindicationsTag()));
    		}
    		info.setFullTag(allObject.toJSONString());
    		
    		userFamilyMemberDao.update(info);
    		this.insertTagFamilyMemberRelation(updateRequest.getUserId(), info.getId(), allObject);
    		
    		response.setInfo(info);
	    	response.setTip("用户家庭成员修改成功");
	    } catch (Exception e) {
	    	log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}
	
	/**
	 * 保存成员与标签关系
	 * @param userId
	 * @param familyMemberId
	 * @param allTags
	 */
	private void insertTagFamilyMemberRelation(Integer userId , Integer familyMemberId , JSONObject allTags){
		//删除旧标签
		HashMap<String,Object> params = new HashMap<String,Object>();
		params.put("eqFamilyMemberId", familyMemberId);
		params.put("eqUserId", userId);
		tagFamilyMemberRelationDao.deleteByMap(params);
		
		//插入新标签
		List<TagFamilyMemberRelation> list = new ArrayList<TagFamilyMemberRelation>();
		for(String key :allTags.keySet()){
			TagFamilyMemberRelation relation = new TagFamilyMemberRelation();
			relation.setFamilyMemberId(familyMemberId);
			relation.setTagId(Integer.valueOf(key));
			relation.setUserId(userId);
			list.add(relation);
		}
		tagFamilyMemberRelationDao.batchInsert(list);	
	}

	@Override
	public Response insert(Request request) throws Exception{
		AddResponse<UserFamilyMember> response = new AddResponse<UserFamilyMember>();
    	
    	try {
    		UserFamilyMemberAddRequest addRequest = (UserFamilyMemberAddRequest)request;
    		UserFamilyMember info = new UserFamilyMember();
    		
    		info.setAgeLowerLimit(addRequest.getAgeLowerLimit());
    		info.setAgeUpperLimit(addRequest.getAgeUpperLimit());
    		info.setDiseaseTag(addRequest.getDiseaseTag());
    		info.setHealthConditionTag(addRequest.getHealthConditionTag());
    		info.setHealthInsuranceInfo(addRequest.getHealthInsuranceInfo());
    		info.setIdentityCard(addRequest.getIdentityCard());
    		info.setIdentityType(addRequest.getIdentityType());
    		info.setMedicationContraindicationsTag(addRequest.getMedicationContraindicationsTag());
    		info.setName(addRequest.getName());
    		info.setOtherTag(addRequest.getOtherTag());
    		info.setRank(addRequest.getRank());
    		info.setRelatives(addRequest.getRelatives());
    		info.setSex(addRequest.getSex());
    		info.setUserId(addRequest.getUserId());
    		info.setAge(addRequest.getAge());
    		info.setStatus(UserFamilyStatusEnum.AVAILABILITY_YES.getId());
    		info.setWeight(addRequest.getWeight());
    		info.setHeight(addRequest.getHeight());
    		info.setPhone(addRequest.getPhone());
    		if(!StringUtil.isEmpty(addRequest.getBirthday())) {
    			info.setBirthday(addRequest.getBirthday());
    		}
    		
    		JSONObject allObject = new JSONObject();
    		if(!StringUtil.isEmpty(info.getDiseaseTag())){
    			allObject.putAll((JSONObject)JSON.parse(info.getDiseaseTag()));
    		}
    		if(!StringUtil.isEmpty(info.getHealthConditionTag())){
    			allObject.putAll((JSONObject)JSON.parse(info.getHealthConditionTag()));
    		}
    		if(!StringUtil.isEmpty(info.getOtherTag())){
    			allObject.putAll((JSONObject)JSON.parse(info.getOtherTag()));
    		}
    		if(!StringUtil.isEmpty(info.getMedicationContraindicationsTag())){
    			allObject.putAll((JSONObject)JSON.parse(info.getMedicationContraindicationsTag()));
    		}
    		info.setFullTag(allObject.toJSONString());
    		userFamilyMemberDao.insert(info);
    		
    		this.insertTagFamilyMemberRelation(addRequest.getUserId(), info.getId(), allObject);
    		
    		response.setInfo(info);
	    	response.setTip("用户家庭成员新增成功");
	    } catch (Exception e) {
	    	log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}

	@Override
	public Response delete(Request request) throws Exception{
		DeleteResponse<UserFamilyMember> response = new DeleteResponse<UserFamilyMember>();
    	
    	try {
    		UserFamilyMemberDeleteRequest deleteRequest = (UserFamilyMemberDeleteRequest)request;
    		UserFamilyMember object = userFamilyMemberDao.selectById(deleteRequest.getId());
    		
	    	if(object.getUserId().intValue() != deleteRequest.getUserId()){
	    		throw new RequestIllegalException("error userId:"+deleteRequest.getUserId());
	    	}
	    	
	    	object.setStatus(UserFamilyStatusEnum.AVAILABILITY_NO.getId());
	    	userFamilyMemberDao.update(object);
	    	response.setTip("用户成员删除成功");
	    } catch (Exception e) {
	    	log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}

	@Override
	public Response getTags(Request request) throws Exception{
		UserFamilyMemberTagShowRequest ufmtsr = (UserFamilyMemberTagShowRequest)request;
		ListResponse<TagBaseInfo> response = new ListResponse<TagBaseInfo>();
		try{
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqUserId", ufmtsr.getUserId());
			params.put("eqFamilyMemberId", ufmtsr.getMemId());
			PageList<TagFamilyMemberRelation>  familyTags = tagFamilyMemberRelationDao.selectByMap(params,false);
			List<Integer> idList = new ArrayList<Integer>();
			for(TagFamilyMemberRelation tmr : familyTags) {
				idList.add(tmr.getTagId());
			}
			
			if(idList.size() > 0) {
				params.clear();
				params.put("inIdList", idList.toArray(new Integer[idList.size()]));
				PageList<TagBaseInfo> tags = tagBaseInfoDao.selectByMap(params, false);
				response.setList(tags);
			}
			return response;
		}catch(Exception e){
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		
	}
}